package com.jiaertangshi.jiaer.service;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import com.jiaertangshi.jiaer.dao.TuserMapper;
import com.jiaertangshi.jiaer.dto.Role;
import com.jiaertangshi.jiaer.dto.Tuser;

/**
 * Created by yangyibo on 17/1/18.
 */

public class CustomUserService implements UserDetailsService { //自定义UserDetailsService 接口

    @Autowired
    TuserMapper  userDao;

    @Override
    public UserDetails loadUserByUsername(String username) { //重写loadUserByUsername 方法获得 userdetails 类型用户
        System.out.println("进入到了权限认证的页面");
        Tuser user = userDao.findByUserName(username);
        if(user == null){
            throw new UsernameNotFoundException("用户名不存在");
        }
        List<SimpleGrantedAuthority> authorities = new ArrayList<>(); //用户权限集合
        for(Role role:user.getRoles())
        {
            authorities.add(new SimpleGrantedAuthority(role.getRoleName()));
            System.out.println(role.getRoleName());
        }
        return new org.springframework.security.core.userdetails.User(user.getTuserName(),
                user.getTuserPwd(), authorities);
    }
    
}